﻿using DtoFw;
using DtoFw.Base;
using DtoFw.Query;
using DtoFw.Result;
using Microsoft.AspNetCore.Mvc;
using Service;
using System.Collections.Generic;
using System.Linq;

namespace SceneEvidenceAPI.Controllers
{
    /// <summary>
    /// 用户
    /// </summary>
    [Route("api/organ")]
    public class MainOrganController : BaseController
    {
        private readonly MainOrganService _organService;
        public MainOrganController(MainOrganService organService)
        {
            this._organService = organService;
        }
        /// <summary>
        /// 查询
        /// </summary>
        /// <returns></returns>
        [HttpGet("pager")]
        public BaseGenericResult<object> Query([FromQuery] OrganQuery query)
        {
            var page = _organService.Query(query);
            var lst = _organService.QueryAll(query);
            return new BaseGenericResult<object>()
            {
                Success = true,
                Code = DtoFw.Enum.EnumReturnCode.Success,
                Data = new { page.Data.TotalCount, page.Data.Data, tree = tree(lst, query.OrganId,0) }
            };
        }
        List<object> tree(List<Domain.Entity.MainOrganEntity> lst,long pid,int lv)
        {
            List<Domain.Entity.MainOrganEntity> _rows;
            var rLs = new List<object>();
            if(lv == 0)
            {
                _rows = lst.Where(v => v.Id == pid).ToList();
            }
            else
            {
                _rows = lst.Where(v => v.SuperiorId == pid).ToList();
            }
            for (int i = 0; i < _rows.Count; i++)
            {
                var _row = _rows[i];
                var children = tree(lst, _row.Id, 1);
                var t = new
                {
                    label = _row.Name,
                    _row.Id,
                    _row.SuperiorId,
                    children
                };
                rLs.Add(t);
            }
            return rLs;
        }
        /// <summary>
        /// 新增机构
        /// </summary>
        /// <returns></returns>
        [HttpPost("post")]
        public BaseResult Post([FromBody] PostOrgnQuery query)
        {
            return _organService.Post(query);
        }
        /// <summary>
        /// 修改机构
        /// </summary>
        /// <returns></returns>
        [HttpPut("put")]
        public BaseResult Put([FromBody] PostOrgnEditQuery query)
        {
            return _organService.Put(query);
        }
        /// <summary>
        /// 删除机构
        /// </summary>
        /// <returns></returns>
        [HttpDelete("delete")]
        public BaseResult Delete([FromBody] DeleteDto query)
        {
            return _organService.Delete(query);
        }
        /// <summary>
        /// 查询单个对象
        /// </summary>
        /// <returns></returns>
        [HttpGet("{organId}")]
        public BaseGenericResult<OrganResult> Get(long organId)
        {
            return _organService.Get(organId);
        }
    }
}
